package com.example.ajshu.dao.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by shu.aojun@qq.com on 2016/10/15-22:08
 * Copyright 2016 ao jun shu
 */
@Repository
public class BaseDao {

    // 参数特性的数据访问模板
    @Autowired
    protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    // 简单数据库访问模板
    @Autowired
    protected JdbcTemplate jdbcTemplate;

    protected Object queryForObject(String sql, RowMapper<?> rowMapper)
    {
        return this.jdbcTemplate.queryForObject(sql, rowMapper);
    }

    protected Object queryForObject(String sql, Map<String, Object> paramMap, RowMapper<?> rowMapper)
    {
        return this.namedParameterJdbcTemplate.queryForObject(sql, paramMap, rowMapper);
    }

    protected List<?> queryForList(String sql, RowMapper<?> rowMapper)
    {
        return this.jdbcTemplate.query(sql, rowMapper);
    }

    protected List<?> queryForList(String sql, Map<String, Object> paramMap, RowMapper<?> rowMapper)
    {
        return this.namedParameterJdbcTemplate.query(sql, paramMap, rowMapper);
    }

    protected int update(String sql)
    {
        return this.jdbcTemplate.update(sql);
    }

    protected int update(String sql, Map<String, Object> paramMap)
    {
        return this.namedParameterJdbcTemplate.update(sql, paramMap);
    }

    protected int insert(String sql, Map<String, Object> paramMap)
    {
        return this.namedParameterJdbcTemplate.update(sql, paramMap);
    }

    protected Map<String, Object> insertAndReturnGeneratedKey(String sql, Map<String, Object> paramMap)
    {
        KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
        this.namedParameterJdbcTemplate.update(sql, new MapSqlParameterSource(paramMap), generatedKeyHolder);
        return generatedKeyHolder.getKeys();
    }

    protected int[] batchInsert(String sql, Map<String, Object>[] paramMaps)
    {
        return this.namedParameterJdbcTemplate.batchUpdate(sql, paramMaps);
    }

    protected int delete(String sql)
    {
        return this.jdbcTemplate.update(sql);
    }
    protected int delete(String sql, Map<String, Object> paramMap)
    {
        return this.namedParameterJdbcTemplate.update(sql, paramMap);
    }

    protected int queryForCount(String sql)
    {
        return this.jdbcTemplate.queryForObject(sql, Integer.class);
    }

    protected int queryForCount(String sql, Map<String, Object> paramMap)
    {
        return this.namedParameterJdbcTemplate.queryForObject(sql, paramMap, Integer.class);
    }
}
